package com.java3_21;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Source {

    //用来判断该哪个线程执行
    private int flag;

    public Source() {
    }

    public Source(int flag) {
        this.flag = flag;
    }

    public int getFlag() {
        return flag;
    }

    public void setFlag(int flag) {
        this.flag = flag;
    }

    private final Lock lock = new ReentrantLock();
    //指定唤醒
    private final Condition condition1 = lock.newCondition();
    private final Condition condition2 = lock.newCondition();
    private final Condition condition3 = lock.newCondition();


    //一般来说方法只写操作内容，而循环放在run方法上

    public void PrintAA() {
        lock.lock();
        try {
            while (flag != 1) {
                try {
                    condition1.await();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            System.out.println("AA");
            flag = 2;
            condition2.signal();
        } finally {
            lock.unlock();
        }
    }

    public void PrintBB() {
        lock.lock();
        try {
            while (flag != 2) {
                try {
                    condition2.await();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            System.out.println("BB");
            flag = 3;
            condition3.signal();
        } finally {
            lock.unlock();
        }
    }

    public void PrintCC() {
        lock.lock();
        try {
            while (flag != 3) {
                try {
                    condition3.await();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            System.out.println("CC");
            flag = 1;
            condition1.signal();
        } finally {
            lock.unlock();
        }
    }

}
